//
//  ZCCancellingStocksViewController.m
//  ZhiChe-Wms
//
//  Created by grj on 2018/12/21.
//  Copyright © 2018 Regina. All rights reserved.
//

#import "ZCCancellingStocksViewController.h"
#import "ZCPutInStorageTableViewCell.h"
#import "UWRQViewController.h"
#import "ZCCancellingStocksDetailViewController.h"

@interface ZCCancellingStocksViewController ()<UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, uwRQDelegate>

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UIButton *scanButton;
@property (nonatomic, strong) UISearchController *searchVC;
@property (nonatomic, strong) UITableViewController *tableViewC;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) ZCCancellingStockModel *cancellingStockModel;

@end

static NSString *cancellingCellID = @"ZCPutInStorageTableViewCell";

@implementation ZCCancellingStocksViewController
#pragma mark - 懒加载
- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, 40)];
        _searchView.backgroundColor = [UIColor whiteColor];
    }
    return _searchView;
}

- (UIButton *)scanButton {
    if (!_scanButton) {
        _scanButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
        [_scanButton setImage:[UIImage imageNamed:@"scanQR"] forState:UIControlStateNormal];
        [_scanButton addTarget:self action:@selector(scanQRCode:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _scanButton;
}

- (UISearchController *)searchVC {
    if (!_searchVC) {
        _searchVC = [[UISearchController alloc] initWithSearchResultsController:self.tableViewC];
        _searchVC.delegate = self;
        _searchVC.searchResultsUpdater = self;
        _searchVC.searchBar.placeholder = @"请输入车架号/订单号";
        _searchVC.searchBar.delegate = self;
        [_searchVC.searchBar addSubview:self.scanButton];
        __weak typeof(self)weakSelf = self;
        [self.scanButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.searchVC.searchBar.mas_right).offset(-15);
            make.centerY.equalTo(weakSelf.searchVC.searchBar.mas_centerY);
        }];
        
    }
    return _searchVC;
}

- (UITableViewController *)tableViewC {
    if (!_tableViewC) {
        _tableViewC = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
        _tableViewC.tableView.delegate = self;
        _tableViewC.tableView.dataSource = self;
        _tableViewC.tableView.showsVerticalScrollIndicator = NO;
        _tableViewC.tableView.showsHorizontalScrollIndicator = NO;
        _tableViewC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableViewC.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableViewC.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableViewC.tableView.scrollIndicatorInsets = _tableViewC.tableView.contentInset;
            _tableViewC.tableView.estimatedRowHeight = 0;
            _tableViewC.tableView.estimatedSectionFooterHeight = 0;
            _tableViewC.tableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_tableViewC.tableView registerClass:[ZCPutInStorageTableViewCell class] forCellReuseIdentifier:cancellingCellID];
        _tableViewC.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        _tableViewC.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    return _tableViewC;
}

- (NSMutableArray *)listArray {
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationItem.title = @"退库任务";
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToForward:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.view addSubview:self.searchView];
    [self.searchView addSubview:self.searchVC.searchBar];
    self.definesPresentationContext = YES;
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.searchVC.searchBar.text.length > 0) {
        [self loadData];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
}


#pragma mark - 按钮点击
- (void)scanQRCode:(UIButton *)sender {
    UWRQViewController *uwVC = [[UWRQViewController alloc] init];
    uwVC.delegate = self;
    [self.navigationController pushViewController:uwVC animated:YES];
}

- (void)backToForward:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UISearchBarViewControllerDelegate
- (void)willDismissSearchController:(UISearchController *)searchController {
    self.scanButton.hidden = NO;
}

- (void)willPresentSearchController:(UISearchController *)searchController {
    self.scanButton.hidden = YES;
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if (searchController.isActive) {
        searchController.searchBar.showsCancelButton = YES;
        UIButton *cancelButton = [searchController.searchBar valueForKey:@"cancelButton"];
        if (cancelButton) {
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
            [cancelButton setTitleColor:ZCColor(0x000000, 0.87) forState:UIControlStateNormal];
        }
    }
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.tableViewC.view addSubview:self.hud];
    [self loadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self.listArray removeAllObjects];
    [self.tableViewC.tableView reloadData];
}

#pragma mark - uwDelegate
- (void)uwRQFinshedScan:(NSString *)result {
    NSArray *arr = [result componentsSeparatedByString:@","];
    NSString *vinParams = [arr lastObject];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:vinParams forKey:@"key"];
    [params setObject:@"SCAN" forKey:@"visitType"];
    NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
    [params setObject:houseId forKey:@"storeHouseId"];
    __weak typeof(self)weakSelf = self;
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
    [self.hud showAnimated:YES];
    [ZCHttpTool postWithURL:CancellingStockDetail params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            if ([responseObject[@"data"] isEqual:[NSNull null]]) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = @"未查询到相关数据";
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }else {
                [weakSelf.hud hideAnimated:YES];
                ZCCancellingStocksDetailViewController *detailVC = [[ZCCancellingStocksDetailViewController alloc] init];
                detailVC.keyId = vinParams;
                detailVC.visitType = @"SCAN";
                [weakSelf.navigationController pushViewController:detailVC animated:YES];
            }
        }else {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = responseObject[@"message"];
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        weakSelf.hud.mode = MBProgressHUDModeText;
        weakSelf.hud.label.text = error.localizedDescription;
        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
    }];
    
    
}

#pragma mark - loadData
- (void)loadData {
    self.currentPage = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@(self.currentPage) forKey:@"current"];
    [params setObject:@(10) forKey:@"size"];
    [params setObject:self.searchVC.searchBar.text forKey:@"condition[key]"];
    NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
    [params setObject:houseId forKey:@"condition[storeHouseId]"];
    
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    [ZCHttpTool postWithURL:CancellingStockList params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            [weakSelf.hud hideAnimated:YES];
            weakSelf.cancellingStockModel = [ZCCancellingStockModel yy_modelWithJSON:responseObject[@"data"]];
            [weakSelf.listArray removeAllObjects];
            [weakSelf.listArray addObjectsFromArray:weakSelf.cancellingStockModel.records];
            [weakSelf.tableViewC.tableView reloadData];
            if (weakSelf.cancellingStockModel.records.count < 10) {
                [weakSelf.tableViewC.tableView.mj_footer resetNoMoreData];
            }
            [weakSelf.tableViewC.tableView.mj_header endRefreshing];
        }else {
            [weakSelf.tableViewC.tableView.mj_header endRefreshing];
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = responseObject[@"message"];
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.tableViewC.tableView.mj_header endRefreshing];
        weakSelf.hud.mode = MBProgressHUDModeText;
        weakSelf.hud.label.text = error.localizedDescription;
        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
    }];
    
}

- (void)loadMoreData {
    self.currentPage++;
    if (self.currentPage <= [self.cancellingStockModel.pages integerValue]) {
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:@(self.currentPage) forKey:@"current"];
        [params setObject:@(10) forKey:@"size"];
        [params setObject:self.searchVC.searchBar.text forKey:@"condition[key]"];
        NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
        [params setObject:houseId forKey:@"condition[storeHouseId]"];
        
        self.hud.mode = MBProgressHUDModeIndeterminate;
        self.hud.label.text = nil;
        [self.hud showAnimated:YES];
        __weak typeof(self)weakSelf = self;
        [ZCHttpTool postWithURL:CancellingStockList params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.cancellingStockModel = responseObject[@"data"];
                [weakSelf.listArray addObjectsFromArray:weakSelf.cancellingStockModel.records];
                if (weakSelf.cancellingStockModel.records.count < 10) {
                    [weakSelf.tableViewC.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableViewC.tableView.mj_footer endRefreshing];
                }
            }else {
                [weakSelf.tableViewC.tableView.mj_footer endRefreshing];
                weakSelf.currentPage--;
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableViewC.tableView.mj_footer endRefreshing];
            weakSelf.currentPage--;
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    }else {
        [self.tableViewC.tableView.mj_footer endRefreshing];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCPutInStorageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cancellingCellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.typeTitle = @"车型";
    cell.statusTitle = @"状态";
    ZCCancellingStockDetailModel *cancelModel = self.listArray[indexPath.section];
    cell.cancellingModel = cancelModel;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(360);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCCancellingStocksDetailViewController *detailVC = [[ZCCancellingStocksDetailViewController alloc] init];
    ZCCancellingStockDetailModel *detailModel = self.listArray[indexPath.row];
    detailVC.keyId = detailModel.cancelId;
    detailVC.visitType = @"CLICK";
    [self.navigationController pushViewController:detailVC animated:YES];
}

@end
